<template>
  <el-card v-loading="upload_loading">
    <div class="launch-board">
      <!-- 左侧上传图片 -->
      <div class="pic-upload">
        <h1 style="font-size: 23px;">商品图片</h1>
        <!-- 分割线 -->
        <el-divider></el-divider>
        <h1 class="upload-tip">
          <el-icon style="margin-right: 5px; font-size: 12px;">
            <Warning />
          </el-icon>
          注意：请上传1张商品缩略图，1~5张详情内展示的轮播图。至少需要1张缩略图，1张轮播图。
        </h1>
        <el-upload class="upload-board" v-model:file-list="fileList" action="#" multiple list-type="picture-card"
          :on-preview="handlePictureCardPreview" :on-remove="handleRemove" ref="upload" :on-change="handleChange"
          :limit="fileNumLimit" :on-exceed="handleExceed" :before-upload="beforeUpload" :auto-upload="false"
          :headers="headers">
          <el-icon>
            <Plus />
          </el-icon>
          <template #tip>
            <div style="font-size: 12px; margin-top:10px; display: flex;">
              <el-icon style="margin-right: 5px;">
                <InfoFilled />
              </el-icon>
              确保图片顺序：第一张图为400×400的缩略图，第二张及往后的为400×400轮播图
            </div>
          </template>
        </el-upload>
        <!-- 模态框查看图片 -->
        <el-dialog v-model="dialogVisible">
          <img :src="dialogImageUrl" alt="Preview Image" class="preview-img" />
        </el-dialog>
      </div>

      <!-- 垂直分割线 -->
      <el-divider direction="vertical" border-style="dashed" class="my-divider"></el-divider>

      <!-- 右侧表单 -->
      <div class="commodity-form">
        <h1 style="font-size: 23px;">商品信息</h1>
        <!-- 分割线 -->
        <el-divider></el-divider>
        <el-form ref="applyCommodityFormRef" :model="commodityForm" label-width="120px" :rules="rules" status-icon>
          <!-- 商品名称 -->
          <el-form-item prop="commodityName" label="商品名称">
            <el-input input-style="text-align: center;" style="width: 83%;" v-model="commodityForm.commodityName" />
          </el-form-item>
          <!-- 商品价格 -->
          <el-form-item prop="price" label="商品价格">
            <!-- 利用element-plus的数字输入 -->
            <el-input-number :precision="2" :controls="false" style="width: 83%;" v-model="commodityForm.price"
              :min="0.01" :max="10000000.00" />
          </el-form-item>
          <!-- 库存量 -->
          <el-form-item prop="stocks" label="商品库存量">
            <!-- 利用element-plus的数字输入 -->
            <el-input-number :controls="false" style="width: 83%;" v-model="commodityForm.stocks" :min="0"
              :max="10000000" />
          </el-form-item>
          <!-- 选择商品类别 -->
          <el-form-item label="商品类型" prop="categoryId">
            <el-tag size="large" style="margin-right: 10px;">{{ selected_category.categoryName }}</el-tag>
            <select-category @confirm="handleConfirm"></select-category>
          </el-form-item>
          <!-- 商品描述 -->
          <el-form-item prop="description" label="商品描述">
            <el-input style="width: 83%;" v-model="commodityForm.description" :autosize="{ minRows: 4 }"
              type="textarea" />
          </el-form-item>

        </el-form>
        <p style="display: flex; justify-content: center;">
          <el-button type="primary" @click="onSubmit">发起申请</el-button>
          <el-button @click="resetForm(applyCommodityFormRef)">重置表单</el-button>
        </p>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, reactive } from 'vue'
import { commodityPrice, commodityStocks } from '../../../validator'
import { useStore } from 'vuex';
import SelectCategory from '../../../components/SelectCategory.vue';

const { proxy } = getCurrentInstance();
const store = useStore();
const applyCommodityFormRef = ref()
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const upload_loading = ref(false)

const selected_category = reactive({
  categoryId: '',
  categoryName: ''
})

// 上传后的文件列表
let fileList = ref([])
// 允许的文件类型
let fileType = ["png", "jpg", "bmp", "jpeg", "gif", "webp"];
// 上传文件大小限制，单位MB
let fileSizeLimit = 10;
// 附件数量限制
let fileNumLimit = 6;
// 请求头
let headers = { "Content-Type": "multipart/form-data" };

// 上传文件之前
const beforeUpload = (file) => {
  console.log('beforeUpload: ', file);
  if (file.type !== "" || file.type != null || file.type !== undefined) {
    // 截取文件的后缀，判断文件类型
    const FileExt = file.name.replace(/.+\./, "").toLowerCase();
    // 计算文件大小是否符合限制
    const isSizeAvail = (file.size / 1024 / 1024) < fileSizeLimit;
    // 如果大小超过限制
    if (!isSizeAvail) {
      this.$showMessage(`上传文件大小不能超过 ${fileSizeLimit}MB!`);
      return false;
    }
    // 如果文件类型不在允许上传的范围内
    if (fileType.includes(FileExt)) {
      return true;
    } else {
      ElMessage.error("上传文件格式不正确!");
      return false;
    }
  }
}

// 超出文件个数的回调
const handleExceed = () => {
  ElMessage({
    showClose: true,
    type: 'warning',
    message: `超出最大上传文件数量${fileNumLimit}的限制！`
  });
}

// 处理移除文件
const handleRemove = (uploadFile, uploadFiles) => {
  fileList.value = uploadFiles;
}

// 处理文件变动
const handleChange = (uploadFile, uploadFiles) => {
  fileList.value = uploadFiles;
}

// 处理Preview
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

// 上传图片的方法
const uploadFile = async () => {
  if (fileList.value.length < 2) {
    ElMessage.warning("请至少上传2张图片！");
    return Promise.reject("too few pictures");
  } else {
    let formData = new FormData();  // 将文件封装进FormData
    fileList.value.forEach(file => {
      formData.append('files', file.raw)
    })
    // 调用上传接口
    let fileNames = await proxy.$api.img.uploadImg(formData);
    commodityForm.pictures = fileNames.data;
    return "ok";
  }
}

const categoryList = ref([]);

let commodityForm = reactive({
  commodityLaunchRequestId: "",
  initiateTime: "",
  processTime: "",
  storeId: store.state.store.manageStoreId,  // 注意
  commodityName: "",
  categoryId: "",
  price: 0.0,
  pictures: [],
  description: "",
  stocks: 0,
  status: 0,
  info: ""
})

const rules = reactive({
  commodityName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 1, max: 12, message: '长度应该在1~12个字符之间', trigger: 'blur' },
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    {
      validator: commodityPrice, trigger: 'blur',
    },
  ],
  stocks: [
    { required: true, message: '请输入商品库存', trigger: 'blur' },
    {
      validator: commodityStocks, trigger: 'blur',
    },
  ],
  categoryId: [
    { required: true, message: '请选择商品类型', trigger: 'blur' },
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 1, max: 128, message: '长度应该在1~128个字符之间', trigger: 'blur' },
  ],
})

// 提交表单
const onSubmit = async () => {
  console.log(commodityForm)
  let valid = await applyCommodityFormRef.value.validate();
  if (valid) {
    upload_loading.value = true;
    // 调用图片上传，并更新文件名
    let uploadRet = await uploadFile().catch(error => {
      console.log(error);
      upload_loading.value = false;
      ElMessage.error({ showClose: true, message: "发起图片上传失败" });
    })
    if (uploadRet === 'ok') {
      let res = await proxy.$api.commodity.applyLaunchRequest(commodityForm).catch(error => {
        console.log(error);
        upload_loading.value = false;
      });
      if (res.status === 200) {
        ElMessage.success({ showClose: true, message: '发起申请成功' });
        // 然后清空一下表单
        // TODO
      }
      upload_loading.value = false;
    }
  } else {
    console.log('表单信息不合法')
  }
}

// 重置表单
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

/**
 * 子组件选择商品类别后确认
 */
const handleConfirm = (category) => {
  commodityForm.categoryId = category.categoryId;
  selected_category.categoryName = category.categoryName;
  selected_category.categoryId = category.categoryId;
}

onMounted(async () => {
  // await getAllCategory();
})

</script>

<style lang="less" scoped>
.launch-board {
  display: flex;

  .pic-upload {
    width: 50%;
    // margin-right: 40px;

    /* 分割线 */

    .el-divider {
      border-top: 2px solid rgba(170, 165, 165, 0.651);
    }

    .upload-tip {
      display: flex;
      margin-bottom: 20px;
    }

    .upload-board {
      padding-left: 45px;
    }

    .preview-img {
      width: 100%;
      border-radius: 10px;
      object-fit: cover;
    }
  }

  .my-divider {
    margin-left: 20px;
    margin-right: 20px;
    height: 500px;
  }

  .commodity-form {
    width: 50%;

    /* 分割线 */

    .el-divider {
      border-top: 2px solid rgba(170, 165, 165, 0.651);
    }
  }
}
</style>